/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <QUrl>
#include "postitemmodel.h"
#include "components/thread.h"
#include "components/chan.h"
#include "components/board.h"
#include "components/post.h"
#include "log.h"

PostItemModel::PostItemModel(Wishmaster::ThreadPtr thread, QObject* parent) : QAbstractListModel(parent)
{
	m_thread = thread;
}

PostItemModel::~PostItemModel()
{
}

int PostItemModel::rowCount(const QModelIndex &parent) const
{
	if(!m_thread)
		return 0;
	return m_thread->getActualPostsCount();
}

void PostItemModel::changed(const Wishmaster::PostId& postId)
{
	if(!m_thread)
		return;
	QModelIndex i = index(m_thread->getPostPosition(postId), 0);
	emit dataChanged(i, i);
}

QVariant PostItemModel::data(const QModelIndex &index, int role) const
{
	if(!m_thread)
		return QVariant();

	if(!index.isValid())
		return QVariant();

	Wishmaster::PostPtr post = m_thread->getPost(index.row());
	if(!post)
		return QVariant();

	switch(role)
	{
		case Qt::DisplayRole:
			return post->text();
	
		case PicLinkRole:
			return QString(); //post->piclink();
		
		case PostIdRole:
			return (uint)post->id().postId();
			
		case PicRole:
//			if(post->pic())
//			{
//				return *post->pic();
//			}
			return QVariant();

		case ThreadRole:
			{
				return QVariant::fromValue((void*)&m_thread);
			}

		default:
			return QVariant();
	}
}

Wishmaster::ThreadPtr PostItemModel::getThread()
{
	return m_thread;
}

void PostItemModel::setThread(Wishmaster::ThreadPtr thread)
{
	m_thread = thread;
	if(m_thread->flag(Wishmaster::Thread::Swapped))
		m_thread->unswap();
	emit reset();
}

